package com.example.fw;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.Select;

import com.example.tests.ContactObject;

public class ContactHelper extends HelperWithWebDriverBase {
	
	public ContactHelper(ApplicationManager manager) {
		super(manager);
	}
	
	public Set<ContactObject> getConacts() {
		manager.getNavigationHelper().openHomePage();
		WebElement form = findElements(By.tagName("form")).get(1);
		List<WebElement> listOfContacts = form.findElements(By.name("selected[]"));
		Set<ContactObject> contacts = new HashSet<ContactObject>();
		for (WebElement checkbox : listOfContacts) {
			String title = checkbox.getAttribute("title");
			title = title.substring("Select (".length(),title.length()-")".length());
			ContactObject contact = new ContactObject()
			.setName(title)
			.setId(checkbox.getAttribute("value"));
			contacts.add(contact);
		}
		return contacts;
	}
	
	public void createContact(ContactObject contactObject) {
		manager.getNavigationHelper().openHomePage();
		initContactCreation();
		fillContactForm(contactObject);
		submitContactCreation();
		//returnToHomePage();
	}
	
	public void deleteContact(int i) {
		
		manager.getNavigationHelper().openMainPage();
		click(By.cssSelector("img[alt=\"Edit\"]"));
		click(By.xpath("(//input[@name='update'])[2]"));
		returnToHomePage();
	}
	
	public void modifyContact(int i, ContactObject contactObject) {
		
		manager.getNavigationHelper().openMainPage();
		initContactModification(i);
		fillContactForm(contactObject);
		submitContactModification();
		
		returnToHomePage();
	}

	private void submitContactModification() {
		
		click(By.name("update"));		
	}

	private void initContactModification(int i) {
		
		click(By.cssSelector("img[alt=\"Edit\"]"));
	}
          
	private void returnToHomePage() {
		click(By.linkText("home page"));
	}

	private void submitContactCreation() {
		click(By.name("submit"));
	}

	private void fillContactForm(ContactObject contactObject) {
		type("firstname", contactObject.firstname);
		type("lastname", contactObject.lastname);
		type("address", contactObject.address);
		type("home", contactObject.home);
		type("mobile", contactObject.mobile);
		type("work", contactObject.work);
		type("email", contactObject.email);
		type("email2", contactObject.email2);
		type("byear", contactObject.byear);
		type("address2", contactObject.address2);
		type("phone2", contactObject.phone2);
		
		select(By.name("bday"), contactObject.bday);
		
		select(By.name("bmonth"), contactObject.bmounth);
	}

	private void select(By locator, String text) {
		new Select(driver.findElement(locator)).selectByVisibleText(text);
	}
	
 	private void initContactCreation() {
 		click(By.linkText("add new"));
	}

}
